# coding=utf-8
from urllib import parse, request

from tools.beanret import BeanRet
from tools.cachedata import CacheData
from tools.cachedataclient import CacheDataClient


def http(url, data=None, method="GET"):
    try:
        cache_data_client = CacheDataClient()
        cache_data = CacheData().toObj(cache_data_client.read())
        postdata = parse.urlencode(data).encode('utf-8')
        # 3.push到服务器
        req = request.Request(url, data=postdata, method=method)
        req.add_header("authorization", cache_data.get_token)
        response = request.urlopen(req)
        result = response.read().decode(encoding='utf-8')
        beanret = BeanRet().toObj(result)
        if beanret.getSuccess:
            refresh_token = response.headers.get("authorization")
            if refresh_token:
                cache_data.token = refresh_token
                cache_data_client.write(cache_data.toJson())
            return True
        else:
            return False
    except:
        return False
